package com.cgah

class SecurityController {
    def userSessionBean;
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    // TODO:  poll these from message properties
    static String loginMissingCredential = "Email Address and Password are reqwired.";
    static String loginInvalidCredential = "Login failed";

    private loginError(errMessage) {
        flash.message = errMessage;
        def customer = new Customer();
        // ok this should be a User class, but for the sake of this assignment we will just stick
        // with Customer for now, until I decide this sux and rector for more generic User.
        //def customer = new Customer()
        render(view: "authenticate", model: customer);
    }

    private gotoHomePage() {
        redirect(controller:"listing",action:"list")
    }


    def index = {
        cache false
        def customer = new Customer()
        render(view:"authenticate", model:customer);
    }

    def login = {
        cache false
        def emailAddress = params.emailAddress;
        def password = params.password;
        if (!emailAddress || !password) {
            loginError(loginMissingCredential);
        } else {
            def query = '''from Customer as c where c.emailAddress = :emailAddress and c.password = :password'''
            def result = Customer.findAll(query, [emailAddress:emailAddress, password:password]);
            if (result.size() == 1) { // one and only 1 dammit!
                //render(view:"/listing/list");
                // TODO:  populate the userSessionBean object with the user object and the roles
                userSessionBean.user = result[0];
                //userSessionBean.isAdmin = userSessionBean.user.isAdmin;
                gotoHomePage();
            } else {
                loginError(loginInvalidCredential);
            }
        }
    }

    def logout = {
        cache false
        userSessionBean.user = null;
        gotoHomePage();
    }

}
